package mongo_utils

import (
	"fmt"
	"log"
	"mongodb_connection_monitor/pkg/cmdb_info"
	"mongodb_connection_monitor/pkg/load_config"
	mysqlutils "mongodb_connection_monitor/pkg/mysql_utils"
	"net/url"
	"time"
	// "mongodb_connection_monitor/pkg/mysql_utils"
)

func getTimeVersion() string {
	currentTime := time.Now()
	formattedTime := currentTime.Format("20060102150405")
	return formattedTime
}

func MongoDBCurrentOper(mongodbInfo cmdb_info.MongoDBInfo) error {
	log.Println(mongodbInfo)
	// var config = load_config.GlobalConfig
	var (
		dbUser     string
		dbPassword string
		authSource string
		dbConfig   *load_config.Config
	)
	status := mongodbInfo.Status
	instanceId := mongodbInfo.InstanceId
	if status != "Running" {
		log.Printf("MongoDB instance %s is not running (%s) \n ", instanceId, status)
		return nil
	}
	dbConfig = load_config.LoadConfig()
	// dbUser = load_config.GlobalConfig.DBConfig.DBUsername
	dbUser = dbConfig.DBConfig.DBUsername
	dbPassword = dbConfig.DBConfig.DBPassword
	authSource = dbConfig.DBConfig.AuthSource
	// dbPassword = load_config.GlobalConfig.DBConfig.DBPassword
	// authSource = load_config.GlobalConfig.DBConfig.AuthSource

	mongoDBConnectInfoList := mongodbInfo.MongoDBConnectInfoList
	escapedPassword := url.QueryEscape(dbPassword)

	for _, mongoDBConnectInfo := range mongoDBConnectInfoList {
		// role := mongoDBConnectInfo.Role
		connectionString := mongoDBConnectInfo.ConnectionString
		time_version := getTimeVersion()
		mongo_role := mongoDBConnectInfo.Role
		// Build the MongoDB connection string
		mongoURI := fmt.Sprintf("mongodb://%s:%s@%s/%s", dbUser, escapedPassword, connectionString, authSource)

		// Connect to MongoDB
		mongoConnect, connectErr := ConnectToMongoDB(mongoURI)
		if connectErr != nil {
			log.Println(connectErr)
			continue
		}

		// 	// Get current operation information
		res, currentOpErr := GetCurrentOp(mongoConnect)
		if currentOpErr != nil {
			log.Println(currentOpErr)
			continue
		}

		var calc_map = CurrentOpHandler(res)
		ConnectOperation(calc_map, mongo_role, time_version, mongodbInfo)

	}
	log.Println("connet check done!")
	return nil
}

func ConnectOperation(calc_map map[string]int, mongoRole string, time_version string, mongodbInfo cmdb_info.MongoDBInfo) {
	var monConnectInfoList []mysqlutils.MongodbConnectionIpInfo
	for con_host, con_count := range calc_map {
		var c mysqlutils.MongodbConnectionIpInfo
		log.Println(con_host, con_count)
		
		c.ConnectIp = con_host
		c.ConnectionCount = con_count
		c.InstanceId = mongodbInfo.InstanceId
		c.TimeVersion = time_version
		c.MongoRole = mongoRole
		monConnectInfoList = append(monConnectInfoList, c)
	}
	mysqlutils.MongodbConnectionIpInfoCreate(&monConnectInfoList)
}
